/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveQueryForms: CommandUtils.GrooveUtilBase
	{
		private string m_SpaceURI;
		private string m_FormsToolURI;
		
		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveQueryForms(i_Arguments));
		}
	
		public GrooveQueryForms(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveQueryForms[PARAMS...]";
			base.HelpMessage = 
				"GrooveQueryForms\r\n\t" + 
				"Executes query against forms tool in specified Groove workspace(s)\r\n" +
				"Parameters:\r\n\t" +
				"/FormsTool=          The Web Services URI for the Groove forms tool\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"[/V                  Verbose output\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_FormsToolURI = base.GetParameterValue("FormsTool");
			if (System.String.IsNullOrEmpty(m_FormsToolURI))
			{
				base.DisplayUsage("You must specify a forms tool.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			//  The format for a Tool URI is:
			//    "/GWS/Groove/2.0/Tools/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2/ToolContainer/vk2xck8tanv5i"
			//
			//  The format for a Space URI is:
			//    "/GWS/Groove/2.0/Spaces/grooveTelespace/fuzvzuaax9wjv72dwfa2sxyd4vabu8bae74s9k2"

			string[] FormsToolURIParts = m_FormsToolURI.Split(new char[]{'/'});
			m_SpaceURI = "/GWS/Groove/2.0/Spaces/grooveTelespace/" + FormsToolURIParts[6];

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			GrooveWebServicesV12Helpers.Space Space = null;

			try
			{
				Space = base.Identity.OpenSpace(m_SpaceURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
				throw Exception;
			}

			GrooveWebServicesV12Helpers.Tool Tool = null;
			
			try
			{
				Tool = Space.OpenTool(m_FormsToolURI);
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to open forms tool: " + Exception.Message);
				throw Exception;
			}

            bool InvalidToolType = 
                (Tool.Type != GrooveWebServicesV12Helpers.Shared.GROOVE_FORMS_TOOL_SUPPORTED_TYPE) &&
                (Tool.Type != GrooveWebServicesV12Helpers.Shared.GROOVE_FORMS2_TOOL_SUPPORTED_TYPE) &&
                (Tool.Type != GrooveWebServicesV12Helpers.Shared.GROOVE_INFOPATH_FORMS_TOOL_SUPPORTED_TYPE);
            
            if (InvalidToolType)
                throw new System.ArgumentException("Invalid tool type: " + Tool.Type);

			string Result;

			System.Collections.Hashtable FormFieldHashTable = new System.Collections.Hashtable();

			if (base.Verbose)
			{
                if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
                {
                    GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;

                    Result = System.String.Format
                        (
                        "<QueryFormsResult URI='{0}' Name='{1}' DesignInitialized='{2}' Unread='{3}' DefaultFormID='{4}' DefaultFormName='{5}' DefaultFormURI='{6}' DefaultViewID='{7}' DefaultViewName='{8}' DefaultViewURI='{9}' DesignTemplateName='{10}' DesignTemplateVersion='{11}' ViewStyle='{12}'>",
                        FormsTool.URI,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.Name),
                        FormsTool.DesignInitialized,
                        FormsTool.IsUnread,
                        FormsTool.ToolProperties.DefaultFormID,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DefaultFormName),
                        FormsTool.ToolProperties.DefaultFormURI,
                        FormsTool.ToolProperties.DefaultViewID,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DefaultViewName),
                        FormsTool.ToolProperties.DefaultViewURI,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DesignTemplateName),
                        FormsTool.ToolProperties.DesignTemplateVersion,
                        FormsTool.ToolProperties.ViewStyle
                        );
                }
                else
                {
                    GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;
                    
                    Result = System.String.Format
                        (
                        "<QueryFormsResult URI='{0}' Name='{1}' DesignInitialized='{2}' Unread='{3}' DefaultFormID='{4}' DefaultFormName='{5}' DefaultFormURI='{6}' DefaultViewID='{7}' DefaultViewName='{8}' DefaultViewURI='{9}' DesignTemplateName='{10}' DesignTemplateVersion='{11}' ViewStyle='{12}'>",
                        FormsTool.URI,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.Name),
                        FormsTool.DesignInitialized,
                        FormsTool.IsUnread,
                        FormsTool.ToolProperties.DefaultFormID,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DefaultFormName),
                        FormsTool.ToolProperties.DefaultFormURI,
                        FormsTool.ToolProperties.DefaultViewID,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DefaultViewName),
                        FormsTool.ToolProperties.DefaultViewURI,
                        CommandUtils.UtilStatic.XMLEncode(FormsTool.ToolProperties.DesignTemplateName),
                        FormsTool.ToolProperties.DesignTemplateVersion,
                        FormsTool.ToolProperties.ViewStyle
                        );
                }

				//  HACK ALERT:  No good way to get all fields, so we will use string substitution below
				Result += "<AllFormFields>_ALLFORMFIELDS_</AllFormFields>";
			}
			else
			{
				Result = System.String.Format
					(
					"<QueryFormsResult URI='{0}' Name='{1}'>",
					Tool.URI,
					CommandUtils.UtilStatic.XMLEncode(Tool.Name)
					);
			}

			//  ------------------------------------------------------------------------------
			//  HACK ALERT:  No good way to get all fields, so we will use string substitution
			
				string AllFormFields = "";

			//  ------------------------------------------------------------------------------

			#region Get Forms Content

			Result += "<Forms>";

            if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;

                System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.Form> FormSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.Form>();
                foreach (GrooveWebServicesV12Helpers.Forms.Form Form in FormsTool.Forms)
                    FormSortedList.Add(Form.Name, Form);

                foreach (GrooveWebServicesV12Helpers.Forms.Form Form in FormSortedList.Values)
                {
                    string FormEntry;

                    if (m_Verbose)
                    {
                        FormEntry = System.String.Format
                            (
                            "<Form Name='{0}' ID='{1}' URI='{2}'>",
                            CommandUtils.UtilStatic.XMLEncode(Form.Name),
                            Form.ID,
                            Form.URI
                            );

                        #region Get Form Fields

                        FormEntry += "<FormFields>";

                        System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.Field> FieldSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.Field>();
                        foreach (GrooveWebServicesV12Helpers.Forms.Field Field in Form.Fields)
                            FieldSortedList.Add(Field.Name, Field);

                        foreach (GrooveWebServicesV12Helpers.Forms.Field Field in FieldSortedList.Values)
                        {
                            string FormField = "<FormField Name='" + Field.Name + "' DataType='" + Field.DataType.ToString() + "'/>";
                            FormEntry += FormField;

                            //  ------------------------------------------------------------------------------
                            //  HACK ALERT:  No good way to get all fields, so we will use string substitution

                            if (!FormFieldHashTable.Contains(Field.Name))
                            {
                                AllFormFields += FormField;
                                FormFieldHashTable[Field.Name] = 1;
                            }

                            //  ------------------------------------------------------------------------------
                        }

                        FormEntry += "</FormFields></Form>";

                        #endregion
                    }
                    else
                    {
                        FormEntry = System.String.Format
                            (
                            "<Form Name='{0}' ID='{1}' URI='{2}'/>",
                            CommandUtils.UtilStatic.XMLEncode(Form.Name),
                            Form.ID,
                            Form.URI
                            );
                    }

                    Result += FormEntry;

                }
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;

                System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.Form> FormSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.Form>();
                foreach (GrooveWebServicesV12Helpers.Forms2.Form Form in FormsTool.Forms)
                    FormSortedList.Add(Form.Name, Form);

                foreach (GrooveWebServicesV12Helpers.Forms2.Form Form in FormSortedList.Values)
                {
                    string FormEntry;

                    if (m_Verbose)
                    {
                        FormEntry = System.String.Format
                            (
                            "<Form Name='{0}' ID='{1}' URI='{2}'>",
                            CommandUtils.UtilStatic.XMLEncode(Form.Name),
                            Form.ID,
                            Form.URI
                            );

                        #region Get Form Fields

                        FormEntry += "<FormFields>";

                        System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.Field> FieldSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.Field>();
                        foreach (GrooveWebServicesV12Helpers.Forms2.Field Field in Form.Fields)
                            FieldSortedList.Add(Field.Name, Field);

                        foreach (GrooveWebServicesV12Helpers.Forms2.Field Field in FieldSortedList.Values)
                        {
                            string FormField = "<FormField Name='" + Field.Name + "' DataType='" + Field.DataType.ToString() + "'/>";
                            FormEntry += FormField;

                            //  ------------------------------------------------------------------------------
                            //  HACK ALERT:  No good way to get all fields, so we will use string substitution

                            if (!FormFieldHashTable.Contains(Field.Name))
                            {
                                AllFormFields += FormField;
                                FormFieldHashTable[Field.Name] = 1;
                            }

                            //  ------------------------------------------------------------------------------
                        }

                        FormEntry += "</FormFields></Form>";

                        #endregion
                    }
                    else
                    {
                        FormEntry = System.String.Format
                            (
                            "<Form Name='{0}' ID='{1}' URI='{2}'/>",
                            CommandUtils.UtilStatic.XMLEncode(Form.Name),
                            Form.ID,
                            Form.URI
                            );
                    }

                    Result += FormEntry;

                }
            }

			Result += "</Forms>";

			#endregion

			//  ------------------------------------------------------------------------------
			//  HACK ALERT:  No good way to get all fields, so we will use string substitution
			
				Result = Result.Replace("_ALLFORMFIELDS_", AllFormFields);

			//  ------------------------------------------------------------------------------

			#region Get Views Content

			//  Get views
			Result += "<Views>";

            if (Tool is GrooveWebServicesV12Helpers.Forms.FormsTool)
            {
                GrooveWebServicesV12Helpers.Forms.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms.FormsTool)Tool;

                System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.View> ViewSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms.View>();
                foreach (GrooveWebServicesV12Helpers.Forms.View View in FormsTool.Views)
                    ViewSortedList.Add(View.Name, View);

                foreach (GrooveWebServicesV12Helpers.Forms.View View in ViewSortedList.Values)
                {
                    string ViewEntry;

                    if (m_Verbose)
                    {
                        ViewEntry = System.String.Format
                            (
                            "<View Name='{0}' ID='{1}' URI='{2}'>",
                            CommandUtils.UtilStatic.XMLEncode(View.Name),
                            View.ID,
                            View.URI
                            );

                        #region Get View Columns

                        ViewEntry += "<ViewColumns>";

                        foreach (GrooveWebServicesV12Helpers.Forms.Column Column in View.Columns)
                            ViewEntry += "<ViewColumn Name='" + Column.Name + "'/>";

                        ViewEntry += "</ViewColumns></View>";

                        #endregion
                    }
                    else
                    {
                        ViewEntry = System.String.Format
                            (
                            "<View Name='{0}' ID='{1}' URI='{2}'/>",
                            CommandUtils.UtilStatic.XMLEncode(View.Name),
                            View.ID,
                            View.URI
                            );
                    }

                    Result += ViewEntry;
                }
            }
            else
            {
                GrooveWebServicesV12Helpers.Forms2.FormsTool FormsTool = (GrooveWebServicesV12Helpers.Forms2.FormsTool)Tool;

                System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.View> ViewSortedList = new System.Collections.Generic.SortedList<string, GrooveWebServicesV12Helpers.Forms2.View>();
                foreach (GrooveWebServicesV12Helpers.Forms2.View View in FormsTool.Views)
                    ViewSortedList.Add(View.Name, View);

                foreach (GrooveWebServicesV12Helpers.Forms2.View View in ViewSortedList.Values)
                {
                    string ViewEntry;

                    if (m_Verbose)
                    {
                        ViewEntry = System.String.Format
                            (
                            "<View Name='{0}' ID='{1}' URI='{2}'>",
                            CommandUtils.UtilStatic.XMLEncode(View.Name),
                            View.ID,
                            View.URI
                            );

                        #region Get View Columns

                        ViewEntry += "<ViewColumns>";

                        foreach (GrooveWebServicesV12Helpers.Forms2.Column Column in View.Columns)
                            ViewEntry += "<ViewColumn Name='" + Column.Name + "'/>";

                        ViewEntry += "</ViewColumns></View>";

                        #endregion
                    }
                    else
                    {
                        ViewEntry = System.String.Format
                            (
                            "<View Name='{0}' ID='{1}' URI='{2}'/>",
                            CommandUtils.UtilStatic.XMLEncode(View.Name),
                            View.ID,
                            View.URI
                            );
                    }

                    Result += ViewEntry;
                }
            }
			
			Result += "</Views>";

			#endregion

			Result += "</QueryFormsResult>";

			//  Load result into xmldocument
			System.Xml.XmlDocument ResultXmlDocument = new System.Xml.XmlDocument();
			ResultXmlDocument.LoadXml(Result);
			ResultXmlDocument.Save(base.StandardOutput);

			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}

	}
}